package com.gupao.javap6.pattern.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 数据源动态切换代理类
 *
 * @author withinfly(45度C)
 * @date 2020/3/1 23:08
 */
public class IDynamicDataSourceProxy implements InvocationHandler {

    private final static String METHOD_ADD = "add";
    private final static String METHOD_DELETE = "delete";
    private final static String METHOD_UPDATE = "update";
    private final static String METHOD_SELECT = "select";

    private IBasicMapper basicMapper;

    public IBasicMapper getMapper(IBasicMapper mapper) {
        this.basicMapper = mapper;
        Class<? extends IBasicMapper> clazz = mapper.getClass();
        return (IBasicMapper) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String name = method.getName().toLowerCase();
        if (name.startsWith(METHOD_ADD)
                || name.startsWith(METHOD_DELETE)
                || name.startsWith(METHOD_UPDATE)) {
            System.out.println("选择数据源：Master .");
        } else {
            System.out.println("选择数据源：Slave .");
        }
        Object invoke = method.invoke(basicMapper, args);
        System.out.println("清除数据源选择，恢复到默认数据源.");
        return invoke;
    }

}
